<template>
  <div class="message-container">
    <h2>消息通知</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="messages.length === 0" class="no-messages">暂无消息</div>
    <ul v-else class="message-list">
      <li v-for="message in messages" :key="message.id" class="message-item" :class="{ 'unread': message.isRead === 2 }">
        <div class="message-content">
          <p>{{ message.content.msg }}</p>
          <p class="message-date">{{ formatDate(message.createdTime) }}</p>
        </div>
        <span v-if="message.isRead === 2" class="unread-tag">未读</span>
        <button @click="navigateToDetail(message.content.targetId)" class="view-detail-btn">
          查看详情
        </button>
      </li>
    </ul>
    <div v-if="hasMorePages" class="load-more">
      <button @click="loadMoreMessages" class="load-more-btn">加载更多</button>
    </div>
  </div>
</template>

<script setup>
import request from "@/utils/request.js";
import { ref, onMounted, computed, onUnmounted } from 'vue';
import dayjs from 'dayjs';
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import WebSocketService from '@/services/WebSocketService.js';

const router = useRouter();
const messages = ref([]);
const loading = ref(true);
const unreadPageNum = ref(1);
const readPageNum = ref(1);
const pageSize = ref(10);
const totalUnread = ref(0);
const totalRead = ref(0);
let webSocketService;

const hasMorePages = computed(() => {
  return (unreadPageNum.value * pageSize.value < totalUnread.value) || (readPageNum.value * pageSize.value < totalRead.value);
});

const loadMessages = (isRead) => {
  const payload = {
    isRead: isRead,
    pageNum: isRead === 2 ? unreadPageNum.value : readPageNum.value,
    pageSize: pageSize.value
  };

  request.post('/circle/share/message/getMessages', payload).then(res => {
    if (res.code === '200') {
      console.log('加载消息成功（isRead=' + isRead + '）:', res);
      if (isRead === 2) {
        messages.value = [...res.data.list, ...messages.value.filter(msg => msg.isRead !== 2)];
        totalUnread.value = res.data.total;
      } else {
        messages.value = [...messages.value.filter(msg => msg.isRead === 2), ...res.data.list];
        totalRead.value = res.data.total;
      }

      // 添加调试信息
      console.log('当前消息列表:', messages.value);
      console.log('总未读消息数:', totalUnread.value);
      console.log('总已读消息数:', totalRead.value);
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('加载消息失败，请稍后再试');
    console.error(err);
  }).finally(() => {
    loading.value = false;
  });
};

const navigateToDetail = (targetId) => {
  router.push(`/front/plantCircleDetail?id=${targetId}`);
};

const loadMoreMessages = () => {
  if (unreadPageNum.value * pageSize.value < totalUnread.value) {
    unreadPageNum.value++;
    loadMessages(2);
  } else if (readPageNum.value * pageSize.value < totalRead.value) {
    readPageNum.value++;
    loadMessages(1);
  }
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};



onMounted(() => {
  loadMessages(2); // 首先加载未读消息
  loadMessages(1); // 然后加载已读消息
});

onUnmounted(() => {
  // 不需要在这里关闭 WebSocket 连接
});
</script>

<style scoped>
.message-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading, .no-messages {
  text-align: center;
  padding: 20px;
}

.message-list {
  list-style-type: none;
  padding: 0;
}

.message-item {
  border-bottom: 1px solid #ccc;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-item.unread {
  background-color: #f9f9ff; /* 浅蓝色背景表示未读 */
}

.message-item.unread .message-content p {
  font-weight: bold; /* 未读消息加粗 */
}

.message-content {
  flex-grow: 1;
  position: relative;
}

.message-date {
  font-size: 0.9em;
  color: #888;
}

.unread-tag {
  margin-right: 10px;
  background-color: #ffcccb;
  color: red;
  padding: 2px 5px;
  border-radius: 4px;
  font-size: 0.8em;
}

.view-detail-btn {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.load-more-btn {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 4px;
}
</style>
